package cn.conac.rc.gateway.modules.user.rest;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.framework.utils.DesUtil;
import cn.conac.rc.framework.utils.FastJsonUtil;
import cn.conac.rc.framework.utils.IpUtils;
import cn.conac.rc.framework.utils.QRUtil;
import cn.conac.rc.framework.utils.ResponseUtils;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.gateway.config.propertiesConfig;
import cn.conac.rc.gateway.modules.ofs.entity.OrganizationEntity;
import cn.conac.rc.gateway.modules.ofs.service.CodeService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.modules.ofs.vo.OrganizationVo;
import cn.conac.rc.gateway.modules.user.entity.OuserEntity;
import cn.conac.rc.gateway.modules.user.entity.RcUserEntity;
import cn.conac.rc.gateway.modules.user.entity.RoleEntity;
import cn.conac.rc.gateway.modules.user.entity.UserAreaEntity;
import cn.conac.rc.gateway.modules.user.entity.UserEntity;
import cn.conac.rc.gateway.modules.user.entity.UserExtEntity;
import cn.conac.rc.gateway.modules.user.service.SmUserMappingService;
import cn.conac.rc.gateway.modules.user.service.UserService;
import cn.conac.rc.gateway.modules.user.vo.RcUserVo;
import cn.conac.rc.gateway.modules.user.vo.UserInfo2Vo;
import cn.conac.rc.gateway.modules.user.vo.UserInfoVo;
import cn.conac.rc.gateway.modules.user.vo.UserMappingVo;
import cn.conac.rc.gateway.security.RedisUtil;
import cn.conac.rc.gateway.security.UserUtils;
import cn.conac.rc.gateway.security.service.AuthCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value="sys/")
@Api(tags="用户信息接口", description="用户信息")
public class UserController {

    @Autowired
    UserService userService;
    
	@Autowired
	OrganizationService orgService;

    @Autowired
    private propertiesConfig properties;

    @Autowired
	RedisUtil redisUtil;

    @Autowired
	AuthCheckUtil authCheckUtil;
    
	@Autowired
	SmUserMappingService userMappingService;
	
	@Autowired
    CodeService codeService;
	
	/**
	 * 文件名长度限制
	 */
	@Value("${importFile.name.maxlength}")
	private int nameMaxlength;

	/**
	 * 允许导入文件后缀
	 */
	@Value("${importFile.allow.suffix}")
	private String allowSuffix;

	/**
	 * 文件最大值限制
	 */
	@Value("${importFile.max.volume}")
	private int maxVolume;
	
	/**
	 * 导入文件支持的行数
	 */
	@Value("${importFile.max.rows}")
	private int maxRows;
	
	/**
	 * 用户导入的初始密码
	 */
	@Value("${user.passwd.init}")
	private String initPasswd;
	
	/**
	 * 用户最后一次登录初始IP
	 */
	@Value("${user.last.login.ip.init}")
	private String initLastLoginIp;
	
	/**
	 * 导入用户的最大长度
	 */
	@Value("${user.fullName.maxLength}")
	private int fullNameMaxLen;
	
	/**
	 * 导入所属科室的最大长度
	 */
	@Value("${user.deptName.maxLength}")
	private int deptNameMaxLen;
	
	/**
	 * 获取编制二维码文本信息的url
	 */
	@Value("${bzewm.api.url}")
	private String bzewmApiUrl;
	
	/**
	 * 编制二维码图片的宽度
	 */
	@Value("${file.qr.code.img.width}")
	private int qrCodeImgWidth;
	
	/**
	 * 编制二维码图片的高度
	 */
	@Value("${file.qr.code.img.height}")
	private int qrCodeImgHeight;
	
	/**
	 * 编制二维码图片的格式
	 */
	@Value("${file.qr.code.img.format}")
	private String qrCodeImgFormat;
	
    @ApiOperation(value = "用户信息保存", httpMethod = "POST", response = JSONObject.class, notes = "用户信息保存<br>" + "1)新增示例如下：<br>" +
    "{<br>\"userEntity\":{<br>\"fileUrl\":\"/u/cms/ea/bf/cc/2b/63/ee/e8/01/xn--26qv4dpwd3zao4ly84ap8k9yo1zh.xn--55qw42g/201604/15161306xuqm.png\",<br>\"nickName\":\"测试昵称\",<br>\"email\":\"test@163.com\",<br>\"deptName\":\"测试科室\",<br>\"isDisabled\":\"0\",<br>\"roleList\":[<br>{<br>\"roleId\":\"107\",<br>\"roleName\":\"编办电子政务中心人员\"<br>}<br>]<br>},<br>\"userExtEntity\":{<br>\"mobile\":\"13599996666\",<br>\"idNumber\":\"123456789012345678\",<br>\"orgId\":\"1087101\",<br>\"fullName\":\"张三\"<br>},<br>\"oUserEntity\":{<br>\"password\":\"123456qwe\",<br>\"confirmPassword\":\"123456qwe\"<br>},<br>\"userAreaEntity\":{<br>\"areaId\":\"C1F1B8D6AAE72993E04011ACAA466E53\",<br>\"areaCode\":\"240000000\"<br>},<br>\"orgDomainName\":\"贵州省编办.政务\"<br>}<br>"
    ) 		
    @RequestMapping(value = "users/c", method = RequestMethod.POST)
    public Object cudUserInfoSave(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "用户信息（icp_user）、用户扩展信息(icp_user_ext)、用户区域(icp_user_area)及用户私密信息(icpo_user)的entity", required = true) 
    		@RequestBody Map<String, Object> entityMap  )
            throws RestClientException, Exception {
    	
		ResultPojo resultInfo = new ResultPojo(); 	 
		UserInfoVo userInfoVo = new UserInfoVo();
		Map<String,String> resultMap = new HashMap<String,String>();
		Integer orgId = null;
		int isAdmin = UserEntity.ORG_DOMAIN_NAME_FLAG; // 默认机构域名（1：机构域名  0：编制域名）
		int domainType = -1;
		String userType =UserExtEntity.USER_TYPE_WBJ; //默认委办局用户类别
		UserEntity userEntity = new UserEntity();
		if(null != entityMap.get("userEntity")) {
			BeanMapper.copy(entityMap.get("userEntity"), userEntity);
		}
		List<RoleEntity> roleList = userEntity.getRoleList();
		if(null != roleList && roleList.size() > 0) {
			RoleEntity roleEntity = roleList.get(0);
			if(null != roleEntity && null != roleEntity.getRoleId()) {
				if(RoleEntity.ROLE_BB.equals(roleEntity.getRoleId().toString())                ||
						RoleEntity.ROLE_BBBZGL.equals(roleEntity.getRoleId().toString())	 ||
						RoleEntity.ROLE_BB_GLY.equals(roleEntity.getRoleId().toString())  ||
						RoleEntity.ROLE_BBPT.equals(roleEntity.getRoleId().toString())  ||
						RoleEntity.ROLE_BBTGSG.equals(roleEntity.getRoleId().toString()) ) {
					userType =UserExtEntity.USER_TYPE_BB;
				} else if(RoleEntity.ROLE_ADMIN_SYS.equals(roleEntity.getRoleId().toString())) {
					userType =UserExtEntity.USER_TYPE_GLY;
				} else if(RoleEntity.ROLE_FZB.equals(roleEntity.getRoleId().toString())) {
	 				userType =UserExtEntity.USER_TYPE_FZB;
	 			} 
			}
		}
		
		//  取得用户扩展信息
		if(null != entityMap.get("userExtEntity")) {
			UserExtEntity userExtEntity = new UserExtEntity();
			BeanMapper.copy(entityMap.get("userExtEntity"), userExtEntity);
			// 设置用户类别
			userExtEntity.setUserType(userType);
			userInfoVo.setUserExtEntity(userExtEntity);
			orgId = userExtEntity.getOrgId();
			if(!StringUtils.isEmpty(userExtEntity.getFullName())) {
				isAdmin = UserEntity.BZ_DOMAIN_NANE_FLAG;
			}
			JSONObject rcUserJson = null;
			// 验证该手机号是否已经注册
			String mobile = userExtEntity.getMobile();
			if(StringUtils.isNotBlank(mobile)) {
				rcUserJson = userService.findByMobile(mobile);
				if(null != rcUserJson.getJSONObject("result")) {
					resultInfo.setCode(ResultPojo.CODE_FAILURE);
					resultInfo.setMsg("该手机号["+mobile + "]已被其他用户注册，请更换其他手机号");
					resultInfo.setResult(null);
				    return resultInfo;
				}
			}
			// 验证该身份证号是否已经注册
			String idNumberStr = userExtEntity.getIdNumber();
			if(StringUtils.isNotBlank(idNumberStr)) {
				rcUserJson = userService.findByIdNumber(idNumberStr);
				if(null != rcUserJson.getJSONObject("result")) {
					resultInfo.setCode(ResultPojo.CODE_FAILURE);
					resultInfo.setMsg("该身份证号["+idNumberStr + "]已被其他用户注册，请确认输入的身份证号是否正确");
					resultInfo.setResult(null);
				    return resultInfo;
				}
			}
		}
		//  取得用户私密信息
		if(null != entityMap.get("oUserEntity")) {
			OuserEntity ouserEntity = new OuserEntity();
			BeanMapper.copy(entityMap.get("oUserEntity"), ouserEntity);
			if(null == ouserEntity.getPassword()) {
				  // 密码为空场合
				  resultInfo.setCode(ResultPojo.CODE_FAILURE);
				  resultInfo.setMsg(OuserEntity.ERROR_MSG_PASSWORD);
				  resultInfo.setResult(null);
			      return resultInfo;
			}
			if(null == ouserEntity.getConfirmPassword()) {
				  // 确认密码为空场合
				  resultInfo.setCode(ResultPojo.CODE_FAILURE);
				  resultInfo.setMsg(OuserEntity.ERROR_MSG_CONFIM_PASSWORD);
				  resultInfo.setResult(null);
			      return resultInfo;
			}
			if(!ouserEntity.getPassword().equals(ouserEntity.getConfirmPassword())) {
				 // 密码和确认密码不相等场合
				  resultInfo.setCode(ResultPojo.CODE_FAILURE);
				  resultInfo.setMsg(OuserEntity.ERROR_MSG_EQUAL_PASSWORD);
				  resultInfo.setResult(null);
			      return resultInfo;
			}
			// 设置加密密码
			ouserEntity.setPassword(DigestUtils.md5Hex(ouserEntity.getPassword()));
			// 设置注册时间
			ouserEntity.setRegisterTime(new Date());
			// 设置注册用户IP
			ouserEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
			ouserEntity.setLastLoginTime(new Date());
			ouserEntity.setLastLoginIp(initLastLoginIp);
			ouserEntity.setLoginCount(0);
			ouserEntity.setErrorCount(0);
			ouserEntity.setActivation(1);
			userInfoVo.setOuserEntity(ouserEntity);
		}
		// 取得域名信息
		if(null != entityMap.get("orgDomainName")) {
			String orgDomainName =  (String)entityMap.get("orgDomainName");
			if(null != orgDomainName) {
				if(orgDomainName.endsWith(UserEntity.ORG_DOMAIN_TYPE_ZY_STR)){
					domainType = UserEntity.ORG_DOMAIN_TYPE_ZY;
				} else if(orgDomainName.endsWith(UserEntity.ORG_DOMAIN_TYPE_GY_STR)){
					domainType = UserEntity.ORG_DOMAIN_TYPE_GY;
				}
			}
			if(null != orgId && StringUtils.isNotBlank(orgDomainName) ) {
				 JSONObject dbOrgInfoJson =  orgService.findById(orgId.toString());
				 OrganizationEntity dbOrgEntity = new OrganizationEntity();

				if (ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code")) ) {
					// 部门库信息取得成功场合
					dbOrgEntity = JSONObject.toJavaObject(dbOrgInfoJson.getJSONObject("result"), OrganizationEntity.class);
					dbOrgEntity.setOrgDomainName(orgDomainName);
					JSONObject  orgInfoJsonObjSave = (JSONObject)JSONObject.toJSON(dbOrgEntity); 
					// 保存机构域名信息
					JSONObject retOrgInfoJson  = orgService.saveOrUpdate(orgInfoJsonObjSave);
					// 判断保存是否成功失败
					 if (!ResultPojo.CODE_SUCCESS.equals(retOrgInfoJson.getString("code")) ) {
						  // 保存失败场合
						  resultInfo.setCode(retOrgInfoJson.getString("code"));
						  resultInfo.setMsg("[service.saveOrUpdate] in function of cudUserInfoSave " + ResultPojo.MSG_FAILURE + "【"  + retOrgInfoJson.getString("msg") + "】" );
						  resultInfo.setResult(null);
					      return resultInfo;
					 }
					 resultMap.put("orgId", orgId.toString());
				}		
			}
		}
		 
		 // 取得用户基本信息
		if(null != entityMap.get("userEntity")) {
			// 设置注册时间
			userEntity.setRegisterTime(new Date());
		   // 设置注册用户ID
			userEntity.setRegisterUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
			// 设置注册用户IP
			userEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
			userEntity.setLastLoginTime(new Date());
			userEntity.setLastLoginIp(initLastLoginIp);
			userEntity.setLoginCount(0);
			// 设置域名类别
			if(domainType != -1) {
				userEntity.setDomainType(domainType);
			}
			userEntity.setIsAdmin(1);
			// 设置区分机构域名和编制域名的Flag
			userEntity.setIsOrgDomain(isAdmin);
			userEntity.setIsDeleted(0);
			userEntity.setIsViewonlyAdmin(0);
			userEntity.setIsSelfAdmin(0);
			userEntity.setFileTotal(0);
			userEntity.setGrain(0);
			userEntity.setRank(0);
			userEntity.setUploadSize(0);
			userEntity.setUploadTotal(0);
			userEntity.setGroupId(1);
			userInfoVo.setUserEntity(userEntity);
		}
		
		//  取得用户区域信息
		if(null != entityMap.get("userAreaEntity")) {
			UserAreaEntity userAreaEntity = new UserAreaEntity();
			BeanMapper.copy(entityMap.get("userAreaEntity"), userAreaEntity);
			userInfoVo.setUserAreaEntity(userAreaEntity);
		}

		// 保存用户信息
		JSONObject retUserInfoJson = userService.saveUserInfo(userInfoVo);
		// 判断保存是否成功失败
	    if (!ResultPojo.CODE_SUCCESS.equals(retUserInfoJson.getString("code")) ) {
			  // 保存失败场合
			  resultInfo.setCode(retUserInfoJson.getString("code"));
			  resultInfo.setMsg("[service.saveOrUpdate] in function of cudUserInfoSave " + ResultPojo.MSG_FAILURE + "【"  + retUserInfoJson.getString("msg") + "】" );
			  resultInfo.setResult(null);
			  // TODO 回滚上一步保存的域名信息
		      return resultInfo;
		 }
	    @SuppressWarnings("unchecked")
		Map<String,String> retUserInfoMap =  retUserInfoJson.getObject("result", Map.class);
	    resultMap.putAll(retUserInfoMap);
		
   	    resultInfo.setCode(ResultPojo.CODE_SUCCESS);
        resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
        resultInfo.setResult(resultMap);
        
        return  resultInfo;
    }
    
    @ApiOperation(value = "用户信息更新", httpMethod = "POST", response = JSONObject.class, notes = "用户信息更新<br>" + "1)新增示例如下：<br>" +
    	    "{<br>\"userEntity\":{<br>\"fileUrl\":\"/u/cms/ea/bf/cc/2b/63/ee/e8/01/xn--26qv4dpwd3zao4ly84ap8k9yo1zh.xn--55qw42g/201604/15161306xuqm.png\",<br>\"nickName\":\"测试昵称\",<br>\"email\":\"test@163.com\",<br>\"deptName\":\"测试科室\",<br>\"isDisabled\":\"0\",<br>\"roleList\":[<br>{<br>\"roleId\":\"107\",<br>\"roleName\":\"编办电子政务中心人员\"<br>}<br>]<br>},<br>\"userExtEntity\":{<br>\"mobile\":\"13599996666\",<br>\"idNumber\":\"123456789012345678\",<br>\"orgId\":\"1087101\",<br>\"fullName\":\"张三\"<br>},<br>\"oUserEntity\":{<br>\"password\":\"123456qwe\",<br>\"confirmPassword\":\"123456qwe\"<br>},<br>\"userAreaEntity\":{<br>\"areaId\":\"C1F1B8D6AAE72993E04011ACAA466E53\",<br>\"areaCode\":\"240000000\"<br>},<br>\"orgDomainName\":\"贵州省编办.政务\"<br>}<br>"
    		+ "2)完善信息步骤一示例如下：<br>" 
    	    + "{<br>\"userExtEntity\":{<br>\"mobile\":\"13999996666\",<br>\"idNumber\":\"623456789012345678\",<br>\"msgpin\":\"123456\"<br>}<br>}<br>"
    	    + "3)完善信息步骤二示例如下：<br>" 
    	    + "{<br>\"userEntity\":{<br>\"nickName\":\"测试昵称55\",<br>\"email\":\"test55@163.com\"<br>},<br>\"oUserEntity\":{<br>\"password\":\"1234qwerty\",<br>\"confirmPassword\":\"1234qwerty\"<br>}<br>}<br>"
    	    +"userId=1044506"
    	    )
    @RequestMapping(value = "users/{userId}/u", method = RequestMethod.POST)
    public Object cudUserInfoUpdate(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam("用户ID") @PathVariable("userId") Integer userId,
            @ApiParam(value = "用户信息（icp_user）、用户扩展信息(icp_user_ext)、用户区域(icp_user_area)及用户私密信息(icpo_user)的entity", required = true) 
            @RequestBody Map<String, Object> entityMap  )
            throws RestClientException, Exception {
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == userId) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ userId of parameter is null ] in function of cudUserInfoUpdate " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
		boolean check = authCheckUtil.authCheckUserId(String.valueOf(userId));
		if(!check){
			// 权限验证失败
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("权限验证失败.");
			resultInfo.setResult(null);
			return resultInfo;
		}
 		UserInfoVo userInfoVo = new UserInfoVo();
 		Map<String,String> resultMap = new HashMap<String,String>();
 		Integer orgId = null;
// 		int isAdmin = UserEntity.ORG_DOMAIN_NAME_FLAG; // 默认机构域名（1：机构域名  0：编制域名）
 		int domainType = -1;
 		String userType = null; //默认委办局用户类别
 		UserEntity userEntity = new UserEntity();
 		if(null != entityMap.get("userEntity")) {
 			BeanMapper.copy(entityMap.get("userEntity"), userEntity);
 		}
 		
 		List<RoleEntity> roleList = userEntity.getRoleList();
 		if(null != roleList && roleList.size() > 0) {
 			RoleEntity roleEntity = roleList.get(0);
 			if(null != roleEntity && null != roleEntity.getRoleId()) {
			   if(RoleEntity.ROLE_BB.equals(roleEntity.getRoleId().toString())                ||
						RoleEntity.ROLE_BBBZGL.equals(roleEntity.getRoleId().toString())	 ||
						RoleEntity.ROLE_BB_GLY.equals(roleEntity.getRoleId().toString())  ||
						RoleEntity.ROLE_BBPT.equals(roleEntity.getRoleId().toString())  ||
						RoleEntity.ROLE_BBTGSG.equals(roleEntity.getRoleId().toString()) ) {
	 				userType =UserExtEntity.USER_TYPE_BB;
	 			} else if(RoleEntity.ROLE_ADMIN_SYS.equals(roleEntity.getRoleId().toString())) {
	 				userType =UserExtEntity.USER_TYPE_GLY;
	 			} else if(RoleEntity.ROLE_FZB.equals(roleEntity.getRoleId().toString())) {
	 				userType =UserExtEntity.USER_TYPE_FZB;
	 			} else if(RoleEntity.ROLE_WBJ.equals(roleEntity.getRoleId().toString())) {
	 				userType =UserExtEntity.USER_TYPE_WBJ;
	 			} 
 			} else {
 				// guard处理前台返回异常的空串
 				userEntity.setRoleList(null);
 			}
 		} else {
 		    // guard处理前台返回异常的空串
 			userEntity.setRoleList(null);
 		}
 		
 		//  取得用户扩展信息
 		UserExtEntity userExtEntity = new UserExtEntity();
 		if(null != entityMap.get("userExtEntity")) {
 			BeanMapper.copy(entityMap.get("userExtEntity"), userExtEntity);
 			// 设置用户类别
 			if(null != userType) {
 				userExtEntity.setUserType(userType);
 			}
 			userInfoVo.setUserExtEntity(userExtEntity);
 			orgId = userExtEntity.getOrgId();
// 			if(StringUtils.isNotBlank(userExtEntity.getFullName())) {
// 				isAdmin = UserEntity.BZ_DOMAIN_NANE_FLAG;
// 			}
 			JSONObject rcUserJson = null;
 			RcUserEntity rcUserEntity = null;
			// 验证该手机号是否已经被其他用户注册
			String mobile = userExtEntity.getMobile();
			//根据用户id查询db中的user信息
			JSONObject userJson = userService.findByUserId(userId);
			RcUserEntity dbuser = FastJsonUtil.getObject(userJson.getJSONObject("result").toJSONString(), RcUserEntity.class);
			// 判断修改的手机号与db的手机号是否一致，如果不一致需要验证redis中的短信验证码
			if(StringUtils.isNotBlank(mobile)) {
				if(StringUtils.isNotBlank(dbuser.getMobile()) && !mobile.equals(dbuser.getMobile())){
					String validateKey = DesUtil.desEncrypt(String.valueOf(userId), null);
					String code = (String) redisUtil.get("RC_SMS_CODE_" + dbuser.getMobile() + validateKey);
					if(StringUtils.isBlank(code) || (!properties.getDefaultVcode().equals(userExtEntity.getMsgcode()) && !code.equals(userExtEntity.getMsgcode()))){
						resultInfo.setCode(ResultPojo.CODE_FAILURE);
						resultInfo.setMsg("该手机号["+dbuser.getMobile() + "]已被篡改或者验证码不正确.");
						resultInfo.setResult(null);
						return resultInfo;
					}
				}
				rcUserJson = userService.findByMobile(mobile);
				if(null != rcUserJson.getJSONObject("result")) {
					rcUserEntity = JSONObject.toJavaObject(rcUserJson.getJSONObject("result"), RcUserEntity.class);
					if(!userId.equals(rcUserEntity.getId())) {
						resultInfo.setCode(ResultPojo.CODE_FAILURE);
						resultInfo.setMsg("该手机号["+mobile + "]已被其他用户注册，请更换其他手机号");
						resultInfo.setResult(null);
					    return resultInfo;
					}else{
						if(mobile.equals(rcUserEntity.getMobile()) && rcUserEntity.getPassword().equals(DigestUtils.md5Hex(properties.getDefaultPwd()))){
							//密码等于初始化密码，修改手机号码的时候，判定db中这条记录是否已经有手机号，这种情况有可能是同名用户
							//同时登录进行完善新信息操作，是一种并发行为，二者同时占用一个用户信息，这时候后修改的提示【操作失败】
							//并且退出到登录页面重新登录
							resultInfo.setCode(ResultPojo.CODE_FAILURE_USER_BINDED);
							resultInfo.setMsg("当前用户已经被同名用户绑定，请退出到登录页面使用初始密码重新登录。");
							resultInfo.setResult(null);
							return resultInfo;
						}
					}
				}
			}
			// 验证该身份证号是否已经被其他用户注册
			String idNumberStr = userExtEntity.getIdNumber();
			if(StringUtils.isNotBlank(idNumberStr)) {
				rcUserJson = userService.findByIdNumber(idNumberStr);
				if(null != rcUserJson.getJSONObject("result")) {
					rcUserEntity = JSONObject.toJavaObject(rcUserJson.getJSONObject("result"), RcUserEntity.class);
					if(!userId.equals(rcUserEntity.getId())) {
						resultInfo.setCode(ResultPojo.CODE_FAILURE);
						resultInfo.setMsg("该身份证号["+idNumberStr + "]已被其他用户注册，请确认输入的身份证号是否正确");
						resultInfo.setResult(null);
					    return resultInfo;
					}
				}
			}
 		}
 		//  取得用户私密信息
 		if(null != entityMap.get("oUserEntity")) {
 			OuserEntity ouserEntity = new OuserEntity();
 			BeanMapper.copy(entityMap.get("oUserEntity"), ouserEntity);
 			//更新场合有可能不修改密码
 			if(null != ouserEntity.getPassword() && null != ouserEntity.getConfirmPassword() ) {
	 			if(!ouserEntity.getPassword().equals(ouserEntity.getConfirmPassword())) {
	 				 // 密码和确认密码不相等场合
	 				  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	 				  resultInfo.setMsg(OuserEntity.ERROR_MSG_EQUAL_PASSWORD);
                    resultInfo.setResult(null);
                    return resultInfo;
                }
                if (ouserEntity.getPassword().equals(properties.getDefaultPwd())) {
                    // 修改密码不能修改成默认密码conac_123456
                    resultInfo.setCode(ResultPojo.CODE_FAILURE);
                    resultInfo.setMsg(OuserEntity.ERROR_MSG_DEFAULT_PASSWORD);
	 				  resultInfo.setResult(null);
	 			      return resultInfo;
	 			}
 			}
 			// 设置加密密码
 			if(null != ouserEntity.getPassword()) {
 				ouserEntity.setPassword(DigestUtils.md5Hex(ouserEntity.getPassword()));
 			}
 			userInfoVo.setOuserEntity(ouserEntity);
 		}
 		// 取得域名信息
 		if(null != entityMap.get("orgDomainName")) {
 			String orgDomainName =  (String)entityMap.get("orgDomainName");
 			if(null != orgDomainName) {
 				if(orgDomainName.endsWith(UserEntity.ORG_DOMAIN_TYPE_ZY_STR)){
					domainType = UserEntity.ORG_DOMAIN_TYPE_ZY;
				} else if(orgDomainName.endsWith(UserEntity.ORG_DOMAIN_TYPE_GY_STR)){
					domainType = UserEntity.ORG_DOMAIN_TYPE_GY;
				}
 			}
 			if(null != orgId && StringUtils.isNotBlank(orgDomainName) ) {
 				 JSONObject dbOrgInfoJson =  orgService.findById(orgId.toString());
 				 OrganizationEntity dbOrgEntity = new OrganizationEntity();

 				if (ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code")) ) {
 					// 部门库信息取得成功场合
 					dbOrgEntity = JSONObject.toJavaObject(dbOrgInfoJson.getJSONObject("result"), OrganizationEntity.class);
 					dbOrgEntity.setOrgDomainName(orgDomainName);
 					JSONObject  orgInfoJsonObjSave = (JSONObject)JSONObject.toJSON(dbOrgEntity); 
 					// 保存机构域名信息
 					JSONObject retOrgInfoJson  = orgService.saveOrUpdate(orgInfoJsonObjSave);
 					// 判断保存是否成功失败
 					 if (!ResultPojo.CODE_SUCCESS.equals(retOrgInfoJson.getString("code")) ) {
 						  // 保存失败场合
 						  resultInfo.setCode(retOrgInfoJson.getString("code"));
 						  resultInfo.setMsg("[service.saveOrUpdate] in function of cudUserInfoSave " + ResultPojo.MSG_FAILURE + "【"  + retOrgInfoJson.getString("msg") + "】" );
 						  resultInfo.setResult(null);
 					      return resultInfo;
 					 }
 					 resultMap.put("orgId", orgId.toString());
 				}		
 			}
 		}
 		 
 		 // 取得用户基本信息
 		if(null != entityMap.get("userEntity")) {
 			// 设置更新时间
 			userEntity.setUpdateDate(new Date());
 		   // 设置更新用户ID
 			userEntity.setUpdateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
 			// 设置域名类别
 			if(domainType != -1) {
 				userEntity.setDomainType(domainType);
 			}
 			// 设置区分机构域名和编制域名的Flag
 			// 更新的时候不更新机构域名或者编制域名
// 			if(StringUtils.isNotBlank(userExtEntity.getFullName())) {
// 				// 设置区分机构域名和编制域名的Flag
// 				userEntity.setIsOrgDomain(isAdmin);
// 			}
 			userInfoVo.setUserEntity(userEntity);
 		}
 		
 		//  取得用户区域信息
 		if(null != entityMap.get("userAreaEntity")) {
 			UserAreaEntity userAreaEntity = new UserAreaEntity();
 			BeanMapper.copy(entityMap.get("userAreaEntity"), userAreaEntity);
 			userInfoVo.setUserAreaEntity(userAreaEntity);
 		}

 		// 保存用户信息
 		JSONObject retUserInfoJson = userService.updateUserInfo(userId, userInfoVo);
 		// 判断保存是否成功失败
 	    if (!ResultPojo.CODE_SUCCESS.equals(retUserInfoJson.getString("code")) ) {
 			  // 保存失败场合
 			  resultInfo.setCode(retUserInfoJson.getString("code"));
 			  resultInfo.setMsg("[service.saveOrUpdate] in function of cudUserInfoSave " + ResultPojo.MSG_FAILURE + "【"  + retUserInfoJson.getString("msg") + "】" );
 			  resultInfo.setResult(null);
 			  // TODO 回滚上一步保存的域名信息
 		      return resultInfo;
 		 }
 	    @SuppressWarnings("unchecked")
 		Map<String,String> retUserInfoMap =  retUserInfoJson.getObject("result", Map.class);
 	    resultMap.putAll(retUserInfoMap);
 	    
    	 resultInfo.setCode(ResultPojo.CODE_SUCCESS);
         resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
         resultInfo.setResult(resultMap);
         
         return  resultInfo;
    }
    
    @ApiOperation(value = "用户信息逻辑删除", httpMethod = "POST", response = JSONObject.class, notes = "用户信息逻辑删除<br>" +"示例如下： <br>"  + 
    		 "{<br>\"userIdList\":[<br>1044513,<br>1044515<br>]<br>}<br>")
    @RequestMapping(value = "users/ud", method = RequestMethod.POST)
    public Object cudUpdateIsDeletedByUserId(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "用户ID的list", required = true) @RequestBody UserInfo2Vo  userInfo2Vo)
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == userInfo2Vo || null == userInfo2Vo.getUserIdList()) {
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ userInfo2Vo or userInfo2Vo.getUserIdList() of parameter is null ] in function of cudUpdateIsDeletedByUserId " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
   	    }
    	 
         // 成功保存部门信息表和部门状态表返回
         return  userService.updateIsDeletedByBatch(userInfo2Vo);
    }
    
    @ApiOperation(value = "用户信息启用/禁用", httpMethod = "POST", response = JSONObject.class, notes = "用户信息启用/禁用<br>" +"示例如下： <br>"  +
       "{<br>\"isDisabled\":1,<br>\"userIdList\":[<br>1044513,<br>1044515<br>]<br>}<br>")
    @RequestMapping(value = "users/active", method = RequestMethod.POST)
    public Object cudUpdateIsDisabledByUserId(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "用户ID的list", required = true) @RequestBody UserInfo2Vo  userInfo2Vo)
            throws RestClientException, Exception {
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == userInfo2Vo || null == userInfo2Vo.getUserIdList() || null == userInfo2Vo.getIsDisabled()) {
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ userInfo2Vo or userInfo2Vo.getUserIdList() or userInfo2Vo.getIsDisabled() of parameter is null ] in function of cudUpdateIsDeletedByUserId " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
  	    }
         // 成功保存部门信息表和部门状态表返回
    	 return  userService.updateIsDisabledByBatch(userInfo2Vo);
    }
    
    @ApiOperation(value = "用户信息列表", httpMethod = "POST", response = JSONObject.class,  notes = "根据条件查询用户信息<br>"+"示例如下： <br>"
         + "{<br>\"page\": 0,<br>\"size\": 10,<br>\"orgName\":\"潍坊市\",<br>\"fullName\":\"研发部\",<br>\"roleId\":106,<br>\"areaId\":\"C1EFF96F63E63266E04011ACAA466AEF\",<br>\"isAdmin\":1<br>}<br>" +
    		"     1)isAdmin区分机构域名和编制域名（1：机构域名  0：编制域名）<br>" + 
    		"     2)支持的其他字段查询(orgDomainName(域名名称)、mobile(手机号)、idNumber(身份证号)、siCode(SI唯一代码))、loginName(登录用户名)<br>")
    @RequestMapping(value = "users/page", method = RequestMethod.POST)
    public JSONObject userListInfo(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "查询条件对象", required = true) @RequestBody RcUserVo rcUserVo)
            throws RestClientException, Exception {
        return  userService.findPageByCondtion(rcUserVo);
    }
    
    @ApiOperation(value = "根据用户ID查询用户信息", httpMethod = "GET", response = JSONObject.class, notes = "根据用户ID查询用户信息")
    @RequestMapping(value = "users/{userId}/r", method = RequestMethod.GET)
    public Object findByUserId(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "用户ID", required = true) @PathVariable("userId") Integer userId)
            throws RestClientException, Exception {
    	 ResultPojo resultInfo = new ResultPojo();
		if(null == userId) {
			// 参数baseId为null场合
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("[ userId of parameter is null ] in function of findByUserId " + ResultPojo.MSG_FAILURE);
			resultInfo.setResult(null);
			return resultInfo;
		}
		boolean check = authCheckUtil.authCheckUserId(String.valueOf(userId));
		if(!check){
			// 权限验证失败
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("权限验证失败.");
			resultInfo.setResult(null);
			return resultInfo;
		}
		// 成功保存部门信息表和部门状态表返回
    	 return  userService.findByUserId(userId);
    }
    
    @ApiOperation(value = "根据手机号查询用户信息", httpMethod = "GET", response = JSONObject.class, notes = "根据手机号查询用户信息")
    @RequestMapping(value = "users/mobiles/{mobileNum}/r", method = RequestMethod.GET)
    public Object findByMobile(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "手机号", required = true) @PathVariable("mobileNum") String mobileNum)
            throws RestClientException, Exception {
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == mobileNum) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ mobileNum of parameter is null ] in function of findByMobile " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
         // 成功保存部门信息表和部门状态表返回
    	 return  userService.findByMobile(mobileNum);
    }
	@ApiOperation(value = "根据手机号查询用户信息", httpMethod = "GET", response = JSONObject.class, notes = "根据手机号查询用户信息")
    @RequestMapping(value = "users/idnumber/{idnumber}/r", method = RequestMethod.GET)
    public Object findByIdCard(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "身份证号", required = true) @PathVariable("idnumber") String idnumber)
            throws RestClientException, Exception {
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(StringUtils.isBlank(idnumber)) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ idnumber of parameter is null ] in function of findByIdCard " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
         // 成功F返回信息
    	 return  userService.findByIdNumber(idnumber);
    }

	@ApiOperation(value = "验证手机短信码", httpMethod = "GET", response = JSONObject.class, notes = "验证手机短信码")
	@RequestMapping(value = "users/mobiles/{mobileNum}/validate/{smsCode}/key/{key}", method = RequestMethod.GET)
	public Object validateMobile(HttpServletRequest request, HttpServletResponse response,
			@ApiParam("手机号码") @PathVariable("mobileNum") String mobileNum,
			@ApiParam("短信验证码") @PathVariable("smsCode") String smsCode,
			@ApiParam("标识") @PathVariable("key") String key)
			throws RestClientException, Exception {
		ResultPojo resultInfo = new ResultPojo();
		resultInfo.setCode(ResultPojo.CODE_SUCCESS);
		resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		resultInfo.setResult(null);
		if(StringUtils.isBlank(mobileNum) || StringUtils.isBlank(smsCode) || StringUtils.isBlank(key)) {
			// 参数baseId为null场合
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("[ mobileNum,smsCode,key of parameter is null ] in function of validateMobile " + ResultPojo.MSG_FAILURE);
			resultInfo.setResult(null);
			return resultInfo;
		}
		String validateKey = DesUtil.desEncrypt(key, null);
		String code = (String) redisUtil.get("RC_SMS_CODE_" + mobileNum + validateKey);
		if(!properties.getDefaultVcode().equals(smsCode) && StringUtils.isBlank(code)){
			//验证码失效
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("验证码错误！");
			resultInfo.setResult(null);
		}else if(!properties.getDefaultVcode().equals(smsCode) && !smsCode.equals(code)){
			//验证码错误
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("验证码错误！");
			resultInfo.setResult(null);
		}
		JSONObject userJson = userService.findByMobile(mobileNum);
		if (userJson.getString("code").equals(ResultPojo.CODE_SUCCESS) && userJson.getJSONObject("result")!=null) {
			//已经绑定
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("手机号码已经绑定！");
			resultInfo.setResult(null);
		}
		return resultInfo;
	}

	@ApiOperation(value = "验证手机短信码", httpMethod = "GET", response = JSONObject.class, notes = "验证手机短信码")
	@RequestMapping(value = "users/mobiles/{mobileNum}/confirm/{smsCode}/key/{key}", method = RequestMethod.GET)
	public Object confirmMobile(HttpServletRequest request, HttpServletResponse response,
			@ApiParam("手机号码") @PathVariable("mobileNum") String mobileNum,
			@ApiParam("短信验证码") @PathVariable("smsCode") String smsCode,
			@ApiParam("标识") @PathVariable("key") String key)
			throws RestClientException, Exception {
		ResultPojo resultInfo = new ResultPojo();
		resultInfo.setCode(ResultPojo.CODE_SUCCESS);
		resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		resultInfo.setResult(null);
		if(StringUtils.isBlank(mobileNum) || StringUtils.isBlank(smsCode) || StringUtils.isBlank(key)) {
			// 参数baseId为null场合
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("[ mobileNum,smsCode,key of parameter is null ] in function of validateMobile " + ResultPojo.MSG_FAILURE);
			resultInfo.setResult(null);
			return resultInfo;
		}
		String validateKey = DesUtil.desEncrypt(key, null);
		String code = (String) redisUtil.get("RC_SMS_CODE_" + mobileNum + validateKey);
		if(!properties.getDefaultVcode().equals(smsCode) && StringUtils.isBlank(code)){
			//验证码失效
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("验证码错误！");
			resultInfo.setResult(null);
		}else if(!properties.getDefaultVcode().equals(smsCode) && !smsCode.equals(code)){
			//验证码错误
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("验证码错误！");
			resultInfo.setResult(null);
		}

		return resultInfo;
	}
	
	@ApiOperation(value = "根据用户ID获取用户头像", httpMethod = "GET",  notes = "根据用户ID获取用户头像")
    @RequestMapping(value = "users/img/{userId}", method = RequestMethod.GET)
    public Object findImgDataByUserId(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "用户ID", required = true) @PathVariable("userId") Integer userId)
            throws RestClientException, Exception {
    	
    	ResultPojo resultInfo = new ResultPojo();
		if(null == userId) {
			// 参数baseId为null场合
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("[ userId of parameter is null ] in function of findImgDataByUserId " + ResultPojo.MSG_FAILURE);
			resultInfo.setResult(null);
			return resultInfo;
		}
		boolean check = authCheckUtil.authCheckUserId(String.valueOf(userId));
		if(!check){
			// 权限验证失败
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("权限验证失败.");
			resultInfo.setResult(null);
			return resultInfo;
		}

		JSONObject jsonUserInfo =  userService.findByUserId(userId);
		if (ResultPojo.CODE_SUCCESS.equals(jsonUserInfo.getString("code")) ) {
			RcUserEntity rcUserEntity = JSONObject.toJavaObject(jsonUserInfo.getJSONObject("result"), RcUserEntity.class);
			// 设置绝对路径
			String absolutePath = StringUtils.isNotBlank(rcUserEntity.getAbsolutePath()) ? rcUserEntity.getAbsolutePath() : StringUtils.EMPTY;
			// 设置相对路径
			String relativePath = StringUtils.isNotBlank(rcUserEntity.getImgUrl()) ? rcUserEntity.getImgUrl() : StringUtils.EMPTY;
			// 拼装完整路径
			String imgFilePath = absolutePath + relativePath;
//			System.out.println("absolutePath=" + absolutePath);
//			System.out.println("relativePath=" + relativePath);
			
			if(StringUtils.isNotBlank(imgFilePath)) {
				// 文件绝对路径获取
				File srcImgFile = new File(imgFilePath);
//				System.out.println("imgFilePath=" + imgFilePath);
				//File srcImgFile = new File("C:\\test.png");
				if(srcImgFile.exists()){
					ResponseUtils.readImgData(request,response,srcImgFile);
					System.out.println("读取用户头像文件成功");
	//				resultInfo.setCode(ResultPojo.CODE_SUCCESS);
	//				resultInfo.setMsg("读取用户头像文件成功");
	//				resultInfo.setResult(srcImgFile.length());
					return null;
				} else {
					resultInfo.setCode(ResultPojo.CODE_FAILURE);
					resultInfo.setMsg("读取用户头像文件不存在。 UserId：" + userId);
					resultInfo.setResult(0);
					return resultInfo;
				}
			} else {
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("读取用户头像文件的路径不存在。 UserId：" + userId);
				resultInfo.setResult(0);
				return resultInfo;
			}
		} else {
			// 取得失败场合
      	  resultInfo.setCode(jsonUserInfo.getString("code"));
      	  resultInfo.setMsg("[userService.findByUserId] in function of findImgDataByUserId " 
      			  						+ ResultPojo.MSG_FAILURE  + "【" + jsonUserInfo.getString("msg") + "】");
      	  resultInfo.setResult(0);
       	  return resultInfo;
		}
    }
	
	@ApiOperation(value = "从实名制同步某一地区编制人员信息，并生成编制码", httpMethod = "GET", response = JSONObject.class, notes = "从实名制同步编制人员信息，并生成编制码")
	@RequestMapping(value = "users/area/syn/{areaCode}", method = RequestMethod.GET)
	public Object synAreaUsers(HttpServletRequest request, HttpServletResponse response,
			@ApiParam("地区code") @PathVariable("areaCode") String areaCode)
			throws RestClientException, Exception {
		System.out.println("用户导入开始,时间" + new Date());
		ResultPojo resultInfo = new ResultPojo(); 
		OrganizationVo vo = new OrganizationVo();
		vo.setAreaCode(areaCode);
		JSONObject orgJson = orgService.findOrgByParam(vo);		
		List<OrganizationEntity> orgList = FastJsonUtil.getList(orgJson.getJSONArray("result").toJSONString(), OrganizationEntity.class);
		if(orgList != null && orgList.size() > 0){
			for(OrganizationEntity org:orgList){
				try {
					String creditCode = org.getLocalCode();
					if(StringUtils.isBlank(creditCode)){
						creditCode = "T";
					}
					this.synOrgUsers(request, response, org.getId(), creditCode, org.getName());
					System.out.println("用户导入成功，机构名称:" + org.getName() + "机构id:" + org.getId());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("用户导入失败，机构名称:" + org.getName() + "机构id:" + org.getId());
				}
			}
		}
		resultInfo.setCode(ResultPojo.CODE_SUCCESS);
		resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		resultInfo.setResult(null);
		System.out.println("用户导入结束,时间" + new Date());
		return resultInfo;
	}
	
	
	@ApiOperation(value = "从实名制同步编制人员信息，并生成编制码", httpMethod = "GET", response = JSONObject.class, notes = "从实名制同步编制人员信息，并生成编制码")
	@RequestMapping(value = "users/syn/{orgId}/{creditCode}/{orgName}", method = RequestMethod.GET)
	public Object synOrgUsers(HttpServletRequest request, HttpServletResponse response,
			@ApiParam("机构ID") @PathVariable("orgId") String orgId,
			@ApiParam("组织机构代码") @PathVariable("creditCode") String creditCode,
			@ApiParam("机构名称") @PathVariable("orgName") String orgName)
			throws RestClientException, Exception {
		ResultPojo resultInfo = new ResultPojo(); 
		
		//从接口中读取机构编制人员信息
		int curPage = 1;
		int pageSize = 100;
		//生成9位机构编码
	    String orgCode;
	    if(!"T".equals(creditCode) && creditCode.length() == 18){
	    	orgCode = creditCode.substring(8,17);
	    }else{
	    	orgCode = orgId;
	    	if(orgCode.length() < 10){
	    		for(int i=0;i<10-orgCode.length();i++){
	    			orgCode = "T".concat(orgCode);
	    		}
	    	}else{
	    		//机构id长度超长
	    		resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("机构id超长！");
				resultInfo.setResult(null);
				return resultInfo;
	    	}
	    }
		try {
			while(true){
				JSONArray object;
				Map<String,RcUserEntity> userMap = new HashMap<String,RcUserEntity>();
				if("T".equals(creditCode)){
					object = userMappingService.getUserMapping(orgName,curPage,pageSize);
				}else{
					object = userMappingService.getUserMapping(creditCode,curPage,pageSize);
					if(object == null || "[]".equals(object.toJSONString())){
						object = userMappingService.getUserMapping(orgName,curPage,pageSize);
					}
				}
				if(object == null || "[]".equals(object.toJSONString())){
					break;
				}else{
					curPage++;
					List<UserMappingVo> users = FastJsonUtil.getList(object.toJSONString(),UserMappingVo.class);
					//查询优化批量查询
					List<String> idNumbersList = new ArrayList<String>();
					if(users != null && users.size() > 0){
						for(UserMappingVo user:users){
							idNumbersList.add(user.getSfzh());
						}
						JSONObject rcUserJson = userService.findByIdNumbers(idNumbersList);
						List<RcUserEntity> userList = JSONObject.parseArray(rcUserJson.getJSONArray("result").toJSONString(), RcUserEntity.class);
						if(userList != null && userList.size() > 0){
							for(RcUserEntity entity:userList){
								userMap.put(entity.getIdNumber(), entity);
							}
						}
						
						//用户保存列表
						List<UserInfoVo> userVoList = new ArrayList<UserInfoVo>();
						for(UserMappingVo user:users){
							//String idNumber = user.getSfzh();
							String empType = "1";
							if("a".equals(user.getBzlx())){
								empType = "1";
							}else if("b".equals(user.getBzlx())){
								empType = "2";
							}else if("c".equals(user.getBzlx()) ||
									  "d".equals(user.getBzlx()) ||
									  "e".equals(user.getBzlx()) ||
									  "f".equals(user.getBzlx()) ||
									  "g".equals(user.getBzlx()) ||
									  "h".equals(user.getBzlx())){
								empType = "3";
							}else if("11".equals(user.getBzlx())){
								empType = "4";
							}else if("12".equals(user.getBzlx())){
								empType = "5";
							}else if("20".equals(user.getBzlx())){
								empType = "6";
							}
							//组织机构代码进行二次检验
							if("T".equals(creditCode) && StringUtils.isNotBlank(user.getUnifyCode()) && orgCode.startsWith("T")){
								orgCode = user.getUnifyCode().substring(8,17);
						    }
							
							//JSONObject rcUserJson = userService.findByIdNumber(idNumber);
							//RcUserEntity rcUserEntity = JSONObject.toJavaObject(rcUserJson.getJSONObject("result"), RcUserEntity.class);
							RcUserEntity rcUserEntity = userMap.get(user.getSfzh());
							if(rcUserEntity != null && rcUserEntity.getId() != null){
								//如果原生成是临时的，但参数组织机构编码为非临时的
								boolean isFormCodeBlank = StringUtils.isBlank(rcUserEntity.getFormCode());
								if(isFormCodeBlank || 
										(!isFormCodeBlank && rcUserEntity.getFormCode().startsWith("RT") && !orgCode.startsWith("T"))){
									//生成用户编制码
									//在编
									if("01".equals(user.getZbzt()) || "02".equals(user.getZbzt())){
										JSONObject EmpCodeJson = codeService.createEmpCode(orgCode, empType);
										if (ResultPojo.CODE_SUCCESS.equals(EmpCodeJson.getString("code"))){
											String empCode = EmpCodeJson.getString("result");
											UserInfoVo userInfo = new UserInfoVo();
											UserExtEntity entity = new UserExtEntity();
											entity.setUserId(rcUserEntity.getId());
											entity.setFormCode(empCode);
											entity.setFormType(user.getBzlxDesp());
											entity.setFormStatus(user.getZbztDesp());
											userInfo.setUserExtEntity(entity);
											userService.updateUserInfo(rcUserEntity.getId(), userInfo);
										}
									}
								}else{
									//不在编的进行编码回收
									if(!"01".equals(user.getZbzt()) && !"02".equals(user.getZbzt())){
										UserInfoVo userInfo = new UserInfoVo();
										UserExtEntity entity = new UserExtEntity();
										entity.setUserId(rcUserEntity.getId());
										entity.setFormCode("");
										entity.setFormType("");
										entity.setFormStatus("");
										userInfo.setUserExtEntity(entity);
										userService.updateUserInfo(rcUserEntity.getId(), userInfo);
										codeService.removeEmpCode(rcUserEntity.getFormCode());
									}
								}
							}else{
								 JSONObject dbOrgInfoJson =  orgService.findById(orgId.toString());
				 				 OrganizationEntity dbOrgEntity = null;
				 				if (ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code")) ) {
				 					// 部门库信息取得成功场合
				 					dbOrgEntity = JSONObject.toJavaObject(dbOrgInfoJson.getJSONObject("result"), OrganizationEntity.class);
				 					UserInfoVo userInfo = new UserInfoVo();
				 					//设置用户信息
								    UserEntity userEntity = new UserEntity();
						            userEntity.setGroupId(1);
									userEntity.setRegisterTime(new Date());
									// 设置注册用户ID
								    userEntity.setRegisterUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
									// 设置注册用户IP
									userEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
									userEntity.setLastLoginTime(new Date());
									userEntity.setLastLoginIp(initLastLoginIp);
									userEntity.setLoginCount(0);
									//编制域名
									userEntity.setIsOrgDomain(UserEntity.BZ_DOMAIN_NANE_FLAG);
									userEntity.setIsAdmin(1);
									userEntity.setIsDeleted(0);
									userEntity.setIsViewonlyAdmin(0);
									userEntity.setIsSelfAdmin(0);
									userEntity.setFileTotal(0);
									userEntity.setGrain(0);
									userEntity.setRank(0);
									userEntity.setUploadSize(0);
									userEntity.setUploadTotal(0);
									userEntity.setIsDisabled(0);
									userEntity.setDeptName(user.getSzjgName());
									//userEntity.setUsername(user.getXm());
									
									List<RoleEntity> roleList = new ArrayList<RoleEntity>();
									RoleEntity roleEntity = new RoleEntity();
									// 设置导入用户的默认角色
									roleEntity.setRoleId(Integer.valueOf(RoleEntity.ROLE_WBJPT));
									roleList.add(roleEntity);
									userEntity.setRoleList(roleList);
									
									userInfo.setUserEntity(userEntity);
									
									// **************用户扩展信息实体**************
									UserExtEntity userExtEntity = new UserExtEntity();
									// 取得编制域名的姓名
						            // userExtEntity.setFullName(fullNameCell.getContents());
						            // 设置绑定部门
						            userExtEntity.setOrgId(Integer.valueOf(orgId));
						            // 设置用户类别 TODO 支持委办局导入时应该要修改
						            userExtEntity.setUserType(UserExtEntity.USER_TYPE_WBJ);
						            userExtEntity.setIdNumber(user.getSfzh());
						            userExtEntity.setFullName(user.getXm());
						            
									if("01".equals(user.getZbzt()) || "02".equals(user.getZbzt())){
										JSONObject EmpCodeJson = codeService.createEmpCode(orgCode, empType);
										if (ResultPojo.CODE_SUCCESS.equals(EmpCodeJson.getString("code"))){
											String empCode = EmpCodeJson.getString("result");
											userExtEntity.setFormCode(empCode);
										}
										userExtEntity.setFormType(user.getBzlxDesp());
										userExtEntity.setFormStatus(user.getZbztDesp());
									}
									
						            userInfo.setUserExtEntity(userExtEntity);							            
						            
						           // **************用户区域信息实体**************
						            UserAreaEntity userAreaEntity = new UserAreaEntity();
						            userAreaEntity.setAreaId(dbOrgEntity.getAreaId());
						            userAreaEntity.setAreaCode(dbOrgEntity.getAreaCode());
						            userInfo.setUserAreaEntity(userAreaEntity);
						            
						            // **************用户私密信息实体**************
						            OuserEntity ouserEntity = new OuserEntity();
									// 设置加密密码 初始密码定义常量
									ouserEntity.setPassword(DigestUtils.md5Hex(initPasswd));
									// 设置注册时间
									ouserEntity.setRegisterTime(new Date());
									// 设置注册用户IP
									ouserEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
									ouserEntity.setLastLoginTime(new Date());
									ouserEntity.setLastLoginIp(initLastLoginIp);
									ouserEntity.setLoginCount(0);
									ouserEntity.setErrorCount(0);
									ouserEntity.setActivation(1);
									//ouserEntity.setUsername(user.getXm());
									userInfo.setOuserEntity(ouserEntity);	
									
									//保存用户信息
								    //userService.saveUserInfo(userInfo);
								    userVoList.add(userInfo);
				 				}
							}
						}
						//保存用户信息列表
						if(userVoList != null && userVoList.size() > 0){
							userService.saveUserInfoList(userVoList);
						}
					}
									
					/*if(users != null && users.size() > 0){
						for(UserMappingVo user:users){
							String idNumber = user.getSfzh();
							String empType = null;
							if("a".equals(user.getBzlx())){
								empType = "1";
							}else if("b".equals(user.getBzlx())){
								empType = "2";
							}else if("c".equals(user.getBzlx())){
								empType = "3";
							}else if("11".equals(user.getBzlx())){
								empType = "4";
							}else if("12".equals(user.getBzlx())){
								empType = "5";
							}else if("20".equals(user.getBzlx())){
								empType = "6";
							}			
							JSONObject rcUserJson = userService.findByIdNumber(idNumber);
							RcUserEntity rcUserEntity = JSONObject.toJavaObject(rcUserJson.getJSONObject("result"), RcUserEntity.class);
							if(rcUserEntity != null && rcUserEntity.getId() != null){
								//如果原生成是临时的，但参数组织机构编码为非临时的
								boolean isFormCodeBlank = StringUtils.isBlank(rcUserEntity.getFormCode());
								if(isFormCodeBlank || 
										(!isFormCodeBlank && rcUserEntity.getFormCode().startsWith("RT") && orgCode.startsWith("T"))){
									//生成用户编制码
									//在编
									if("01".equals(user.getZbzt()) || "02".equals(user.getZbzt())){
										JSONObject EmpCodeJson = codeService.createEmpCode(orgCode, empType);
										if (ResultPojo.CODE_SUCCESS.equals(EmpCodeJson.getString("code"))){
											String empCode = EmpCodeJson.getString("result");
											UserInfoVo userInfo = new UserInfoVo();
											UserExtEntity entity = new UserExtEntity();
											entity.setUserId(rcUserEntity.getId());
											entity.setFormCode(empCode);
											entity.setFormType(user.getBzlx());
											entity.setFormStatus(user.getZbzt());
											userInfo.setUserExtEntity(entity);
											userService.updateUserInfo(rcUserEntity.getId(), userInfo);
										}
									}
								}else{
									//不在编的进行编码回收
									if(!"01".equals(user.getZbzt()) && !"02".equals(user.getZbzt())){
										UserInfoVo userInfo = new UserInfoVo();
										UserExtEntity entity = new UserExtEntity();
										entity.setUserId(rcUserEntity.getId());
										entity.setFormCode("");
										entity.setFormType("");
										entity.setFormStatus("");
										userInfo.setUserExtEntity(entity);
										userService.updateUserInfo(rcUserEntity.getId(), userInfo);
										codeService.removeEmpCode(rcUserEntity.getFormCode());
									}
								}
							}else{
								 JSONObject dbOrgInfoJson =  orgService.findById(orgId.toString());
				 				 OrganizationEntity dbOrgEntity = null;
				 				if (ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code")) ) {
				 					// 部门库信息取得成功场合
				 					dbOrgEntity = JSONObject.toJavaObject(dbOrgInfoJson.getJSONObject("result"), OrganizationEntity.class);
				 					UserInfoVo userInfo = new UserInfoVo();
				 					//设置用户信息
								    UserEntity userEntity = new UserEntity();
						            userEntity.setGroupId(1);
									userEntity.setRegisterTime(new Date());
									// 设置注册用户ID
								    userEntity.setRegisterUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
									// 设置注册用户IP
									userEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
									userEntity.setLastLoginTime(new Date());
									userEntity.setLastLoginIp(initLastLoginIp);
									userEntity.setLoginCount(0);
									//编制域名
									userEntity.setIsOrgDomain(UserEntity.BZ_DOMAIN_NANE_FLAG);
									userEntity.setIsAdmin(1);
									userEntity.setIsDeleted(0);
									userEntity.setIsViewonlyAdmin(0);
									userEntity.setIsSelfAdmin(0);
									userEntity.setFileTotal(0);
									userEntity.setGrain(0);
									userEntity.setRank(0);
									userEntity.setUploadSize(0);
									userEntity.setUploadTotal(0);
									userEntity.setIsDisabled(0);
									userEntity.setDeptName(user.getSzjgName());
									//userEntity.setUsername(user.getXm());
									
									List<RoleEntity> roleList = new ArrayList<RoleEntity>();
									RoleEntity roleEntity = new RoleEntity();
									// 设置导入用户的默认角色
									roleEntity.setRoleId(Integer.valueOf(RoleEntity.ROLE_WBJPT));
									roleList.add(roleEntity);
									userEntity.setRoleList(roleList);
									
									userInfo.setUserEntity(userEntity);
									
									// **************用户扩展信息实体**************
									UserExtEntity userExtEntity = new UserExtEntity();
									// 取得编制域名的姓名
						            // userExtEntity.setFullName(fullNameCell.getContents());
						            // 设置绑定部门
						            userExtEntity.setOrgId(Integer.valueOf(orgId));
						            // 设置用户类别 TODO 支持委办局导入时应该要修改
						            userExtEntity.setUserType(UserExtEntity.USER_TYPE_WBJ);
						            userExtEntity.setIdNumber(user.getSfzh());
						            userExtEntity.setFullName(user.getXm());
						            
									if("01".equals(user.getZbzt()) || "02".equals(user.getZbzt())){
										JSONObject EmpCodeJson = codeService.createEmpCode(orgCode, empType);
										if (ResultPojo.CODE_SUCCESS.equals(EmpCodeJson.getString("code"))){
											String empCode = EmpCodeJson.getString("result");
											userExtEntity.setFormCode(empCode);
										}
										userExtEntity.setFormType(user.getBzlx());
										userExtEntity.setFormStatus(user.getZbzt());
									}
									
						            userInfo.setUserExtEntity(userExtEntity);							            
						            
						           // **************用户区域信息实体**************
						            UserAreaEntity userAreaEntity = new UserAreaEntity();
						            userAreaEntity.setAreaId(dbOrgEntity.getAreaId());
						            userAreaEntity.setAreaCode(dbOrgEntity.getAreaCode());
						            userInfo.setUserAreaEntity(userAreaEntity);
						            
						            // **************用户私密信息实体**************
						            OuserEntity ouserEntity = new OuserEntity();
									// 设置加密密码 初始密码定义常量
									ouserEntity.setPassword(DigestUtils.md5Hex(initPasswd));
									// 设置注册时间
									ouserEntity.setRegisterTime(new Date());
									// 设置注册用户IP
									ouserEntity.setRegisterIp(IpUtils.getRemoteAddr(request));
									ouserEntity.setLastLoginTime(new Date());
									ouserEntity.setLastLoginIp(initLastLoginIp);
									ouserEntity.setLoginCount(0);
									ouserEntity.setErrorCount(0);
									ouserEntity.setActivation(1);
									//ouserEntity.setUsername(user.getXm());
									userInfo.setOuserEntity(ouserEntity);	
									
									//保存用户信息
								    userService.saveUserInfo(userInfo);								
				 				}
							}
						}
					}*/
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resultInfo.setCode(ResultPojo.CODE_SUCCESS);
		resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		resultInfo.setResult(null);
		return resultInfo;
	}
	
	@ApiOperation(value = "根据用户ID生成二维码图片文件流", httpMethod = "GET",  notes = "根据用户ID生成二维码图片文件流")
    @RequestMapping(value = "users/qrcode/{userId}", method = RequestMethod.GET)
    public Object createQRCodeByUserId(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "用户ID", required = true) @PathVariable("userId") Integer userId)
            throws RestClientException, Exception {
    	
    	ResultPojo resultInfo = new ResultPojo();
		if(null == userId) {
			// 参数baseId为null场合
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("[ userId of parameter is null ] in function of createQRCodeByUserId " + ResultPojo.MSG_FAILURE);
			resultInfo.setResult(null);
			return resultInfo;
		}

		JSONObject jsonUserInfo =  userService.findByUserId(userId);
		if (ResultPojo.CODE_SUCCESS.equals(jsonUserInfo.getString("code")) ) {
			RcUserEntity rcUserEntity = JSONObject.toJavaObject(jsonUserInfo.getJSONObject("result"), RcUserEntity.class);
			if(StringUtils.isNotBlank(rcUserEntity.getFormCode()) 
					&& StringUtils.isNotBlank(rcUserEntity.getFormStatus()) 
					&& StringUtils.isNotBlank(rcUserEntity.getFormType()) ) {
				if(StringUtils.isNotBlank(rcUserEntity.getIdNumber()) 
						&& StringUtils.isNotBlank(rcUserEntity.getFullName())) {
					 String codeKeyStr = rcUserEntity.getIdNumber() + rcUserEntity.getFullName();
					 String md5Code = DigestUtils.md5Hex(codeKeyStr).toUpperCase();
					//md5Code ="E131B2C8EAE2C0E095A4341333672247";
					 String content = bzewmApiUrl + md5Code;
					 Map<EncodeHintType,Object>  qrAttrMap = new Hashtable<EncodeHintType,Object>(); 
				        //内容所使用编码 
					 qrAttrMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
					 qrAttrMap.put(EncodeHintType.MARGIN, 0); 
			         BitMatrix bitMatrix = new MultiFormatWriter().encode(content, 
			                BarcodeFormat.QR_CODE, qrCodeImgWidth, qrCodeImgHeight, qrAttrMap);
			         ServletOutputStream outStream = response.getOutputStream();
			 		 java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(outStream);
			         QRUtil.writeToStream(bitMatrix, qrCodeImgFormat, bos);
				}
			}
			return null;
		} else {
			// 取得失败场合
      	  resultInfo.setCode(jsonUserInfo.getString("code"));
      	  resultInfo.setMsg("[userService.findByUserId] in function of createQRCodeByUserId " 
      			  						+ ResultPojo.MSG_FAILURE  + "【" + jsonUserInfo.getString("msg") + "】");
      	  resultInfo.setResult(0);
       	  return resultInfo;
		}
    }

}
